import time
from loguru import logger

from ai.chat_ai import get_chat_result
from api.alapi import  get_daily_report_format,get_tian_dog_format
from service.common.weibo import get_web_post_list, push_weibo_comment, get_weibo_comment_reply_list, \
    push_weibo_comment_reply, push_weibo_post
from service.db.weibo_post_comment import is_comment, comment
from concurrent.futures import ThreadPoolExecutor


def auto_random_weibo_comment(res):
    """
    微博随机自动化评论
    :param res:
    :return:
    """
    logger.info('[√] 正在执行微博随机自动化评论任务...')
    start_time = time.time()
    lis = get_web_post_list(tye=1)
    if len(lis) == 0:
        logger.warning('[×] 获取微博列表帖子为空')
        return
    with ThreadPoolExecutor(max_workers=1) as executor:
        # 收集任务
        tasks = [executor.submit(auto_weibo_comment, i) for i in lis]

        # 执行任务
        for task in tasks:
            task.result()

    end_time = time.time()
    logger.info(f'[√] 获取微博随机自动化评论耗时: {end_time - start_time:.2f}s')


def auto_weibo_comment(i):
    """
    微博自动化评论帖子
    :param i:  帖子信息
    :return:
    """

    # 判断是否已经评论
    if is_comment(post_id=i['id']):
        logger.warning(f'[×] 帖子 {i["content"]} 已被评论过了')
        return

    # 调用聊天AI
    chat_msg = get_chat_result(i['content'])
    comment_result = push_weibo_comment(i['id'], chat_msg, i['uid'])
    if not comment_result:
        logger.error(f'[×] 评论失败: {i["content"]}')
        return
    # 评论成功后写入到数据库
    info = {
        'uid': i['uid'],
        'post_id': i['id'],
        'post_content': i['content'],
        'comment': chat_msg,
    }
    if comment(info):
        logger.info(f'[√] 评论成功: {i["content"]}')
        time.sleep(5)
    else:
        logger.error(f'[×] 评论失败: {i["content"]}')


def auto_weibo_comment_reply(res):
    """
    微博收到的评论自动化评论
    :param res:
    :return:
    """
    weibo_comment_list = get_weibo_comment_reply_list()
    logger.info('[√] 正在执行微博收到的评论自动化评论任务...')
    if len(weibo_comment_list) == 0:
        logger.warning('[×] 获取微博收到的评论列表为空')
        return
    start_time = time.time()
    for i in weibo_comment_list:
        # 判断是否已经评论
        if is_comment(post_id=f"{i['post_id']}-{i['cid']}"):
            continue
            # 调用聊天AI
        chat_msg = get_chat_result(i['content'])
        res = push_weibo_comment_reply(i['post_id'], i['cid'], chat_msg)
        if not res:
            logger.error(f'[×] 回复失败: {i["content"]}')
            continue
            # 评论成功后写入到数据库
        info = {
            'uid': i['uid'],
            'post_id': f"{i['post_id']}-{i['cid']}",
            'post_content': i['content'],
            'comment': chat_msg,
        }
        if comment(info):
            logger.info(f'[√] 评论成功: {chat_msg}')

    end_time = time.time()
    logger.info(f'[√] 获取微博收到的评论自动化评论耗时: {end_time - start_time:.2f}s')


def auto_weibo_post(params):
    """
    微博发布
    :param params: 接收的参数
    :return:
    """
    post_type = params.get("post_type", 1)
    content = params.get("content", "")
    if post_type == 2:
        # 每日早报
        content = get_daily_report_format()

    if post_type == 3:
        # 舔狗日记
        content = get_tian_dog_format()

    if not content:
        logger.error("[×] 微博发布内容不能为空")
        return
    res = push_weibo_post(content)
    if res:
        logger.info(f'[√] 微博发布成功')
